package com.zjh.config;

import com.zjh.Service.UserServiceImpl;
import com.zjh.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserServiceImpl userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权");

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // simpleAuthorizationInfo.addStringPermission("user:add");

        Subject subject = SecurityUtils.getSubject();
        //从认证里拿的user
        User currentUser = (User) subject.getPrincipal();
        //从数据库拿取当前用户权限
        simpleAuthorizationInfo.addStringPermission(currentUser.getPerms());


        return simpleAuthorizationInfo;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证");

        //把用户名和密码封装到UsernamePasswordToken对象中
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;

        User user = userService.queryUserByName(userToken.getUsername());

        if (user == null) {
            return null;
        }

        if (!userToken.getUsername().equals(user.getName())) {
            //用户名不存在
            return null;
        }

        return new SimpleAuthenticationInfo(user, user.getPwd(), "");
    }
}
